
var layer = layui.layer //弹层
    ,table = layui.table //表格
    ,form = layui.form,$ = layui.jquery,laydate = layui.laydate;
layui.use(['tableEdit',"excel","selectInput"], function () {
    let tableEdit = layui.tableEdit;
    let layer = layui.layer,
        excel = layui.excel,
        selectInput = layui.selectInput;

    lay('.starttime').each(function () {
        laydate.render({
            elem: this
        });
    });

    function getAllJson(jsons) {
        let tmpitem = []
        for (let item of jsons) {
            let tmparr = {}
            tmparr["value"] = item["code"];
            tmparr["name"] = item["name"];
            if (item["users"]) {
                for (let it of item["users"]) {
                    item["list"].push(it)
                }
            }
            if (item["list"] && item["list"].length) {
                tmparr["children"] = getAllJson(item["list"]);
                tmpitem.push(tmparr)
            } else {
                tmpitem.push(tmparr)
            }

        }
        return tmpitem
    }

    function getxmselect(el, name, data) {
        return xmSelect.render({
            el: el,
            name: name,
            filterable: true,       //搜索
            tree: {
                show: true,
                showLine: true,
                showFolderIcon: true,
                indent: 20,
                expandedKeys: false
            },
            height: 'auto',
            data: data,
            on: function ({arr, change, isAdd}) {
                return this
            }
        })
    }
    function getxmselectUser(el, name, data) {
        return xmSelect.render({
            el: el,
            name: name,
            initValue:[user.code],
            tree: {
                show: true,
                showLine: true,
                showFolderIcon: true,
                indent: 20,
                expandedKeys: false
            },
            height: 'auto',
            data: data,
            on: function ({arr, change, isAdd}) {
                return this
            }
        })
    }
    let operationList=[];
    let salesmanList=[];
    let deliveryDateTypeList=[];
    let deptSalesmanList=[];
    let deptOperationList=[];
    let productDataTypeList=[];
    let billNoStatusList=[];
    layer.ready(function () {
        //获取当前用户的部门及人员结构树
        let treeList = getCurrentDepartmentUser();

        if (treeList && treeList.list) {
            let userTree = getAllJson(treeList.list);
            operationList= getxmselectUser("#operationCode", "operationCode", userTree);
            salesmanList= getxmselectUser("#salesmanCode","salesmanCode", userTree);
        } else {
            operationList= getxmselectUser("#operationCode", "operationCode", [{name: user.name, value: user.code}])
            salesmanList= getxmselectUser("#salesmanCode","salesmanCode", [{name: user.name, value: user.code}]);
        }
        //获取当前用户所属部门树()
        let currentDeptTreeList = getAllUserDepartmentTree();
        if (currentDeptTreeList && currentDeptTreeList.list) {
            let deptTree = getAllJson(currentDeptTreeList.list);
            deptOperationList = getxmselectUser("#deptOperationCode", "deptOperationCode", deptTree);
            deptSalesmanList = getxmselectUser("#deptSalesmanCode", "deptSalesmanCode", deptTree);
        } else {
            deptOperationList = getxmselectUser("#deptOperationCode", "deptOperationCode", [{name: user.name, value: user.code}]);
            deptSalesmanList = getxmselectUser("#deptSalesmanCode", "deptSalesmanCode", [{name: user.name, value: user.code}]);
        }
        //供应商
        $.ajax({
            url: "customer2/getAllInspectUnit",
            success: function (res) {
                if (res.status == 200) {
                    $.each(res.data, function (index, item) {
                        $("#supplierCode").append(new Option(item.name, item.code));
                    });
                    form.render('select');
                } else {
                    layer.msg(res.msg, {icon: 5});
                }
            }
        });

        //发货日期
        let deliveryDateType = [
            {name: "采购未维护反馈交期", value: "1"},
            {name: "已超过3月交货期", value: "2"},
            {name: "已正常发货", value: "3"},
            {name: "未到最后交货日期", value: "4"},
        ];
        deliveryDateTypeList = getxmselect("#deliveryDateTypeStr", "deliveryDateTypeStr", deliveryDateType);

        //采购类型
        let productDataType = [
            {name: "成品", value: "1"},
            {name: "配件", value: "2"},
            {name: "备货", value: "3"},
            {name: "外销", value: "4"},
            {name: "样品", value: "5"},
        ];
        productDataTypeList = getxmselect("#productType", "productType", productDataType);

        //单据信息
        let billNoStatus = [
            {name: "草稿箱", value: "1"},
            {name: "待批箱", value: "2,2.1"},
            {name: "已批箱", value: "3"},
            {name: "终止箱", value: "6"},
            {name: "完成箱", value: "4"}
        ];
        billNoStatusList= getxmselect("#status", "status", billNoStatus);



    });
    form.render();//表单刷新

    table.render({
        elem: '#purchase2Select'
        , data: []
        , toolbar: '#purchase2Toolbar'
        ,totalRow: true
        , cols: [[
            //以采购产品表为主
            {field: 'numbers',width: 50,type:'numbers',title:'序号', totalRowText: '合计'}
            ,{field: 'status', title: '单据类型', sort: true, width: 200}
            ,{field: 'operationName', title: '下单人', sort: true, width: 200}
            ,{field: 'salesmanName', title: '业务员', sort: true, width: 200}
            ,{field: 'signingCompanyName', title: '签约公司', sort: true, width: 200}
            , {field: 'paymentType', title: '价格条款', sort: true, width: 120}
            , {field: 'taxIncluded', title: '是否含税', sort: true, width: 120}
            , {field: 'earnestRate', width: 120, title: '定金比例', sort: true}
            , {field: 'earnestMoney', width: 120, title: '定金总额', sort: true}
            , {field: 'abbreviation', title: '客户简称', sort: true, width: 300}
            , {field: 'customerLevelName', title: '客户等级', sort: true, width: 200}
            , {field: 'signingDateStr', title: '下单日期', sort: true, width: 200}
            , {field: 'feedbackDeliveryDateStr', title: '供应商反馈交期', sort: true, width: 200}
            , {field: 'deliveryDateTypeStr', title: '发货日期', sort: true, width: 200}
            , {field: 'actualDeliveryDateStr', title: '实际交期', sort: true, width: 200}
            , {field: 'requestDeliveryDateStr', title: '要求交货期', sort: true, width: 200}
            , {field: 'shipmentNo', title: '出运计划发票号', sort: true, width: 200}
            , {field: 'invoiceNo', title: '出运明细发票号', sort: true, width: 200}
            , {field: 'purchaseNo', title: '采购单号', sort: true, width: 250, totalRow: true}
            , {field: 'supplierName', title: '供应商名称', sort: true, width: 200}
            , {field: 'isFirstTime', title: '是否第一次', sort: true, width: 200}
            , {field: 'contractNo', title: 'PO NO. ', sort: true, width: 200}
            , {field: 'productNo', title: '采购产品编码', sort: true, width: 200}
            , {field: 'materialSupplier', title: '素材供应商', sort: true, width: 200}
            , {field: 'sourceProductNo', title: '源产品编码', sort: true, width: 200}
            , {field: 'specNo', title: '产品规格', sort: true, width: 300}
            , {field:'chineseName', title:'中文名称',width: 200}
            , {field:'chineseDesc', title:'中文描述',width: 200}
            , {field:'englishDesc', title:'英文描述',width: 200}
            , {field: 'amount', title: '订单数量', sort: true, width: 120, totalRow: true}
            , {field: 'planAmount', title: '已交货数量', sort: true, width: 120, totalRow: true}
            , {field: 'unPlanAmount', title: '未交货数量', sort: true, width: 120, totalRow: true}

            , {field: 'purchaseCost', title: '采购成本', sort: true, width: 120, totalRow: true}
            , {field: 'unDeliveredTotal', title: '未交货产品总额', sort: true, width: 120, totalRow: true}

            , {field: 'priceSubtotal', title: '成本金额小计', sort: true, width: 200, totalRow: true}
            , {field: 'productType', title: '采购类型', sort: true, width: 120}
            , {field: 'remark', title: '采购备注', sort: true, width: 200}
            , {field: 'description', title: '反馈备注', sort: true, width: 200}
        ]]
        , id: 'offertableid'
        , height: $(document).height() - $('#purchase2Select').offset().top - 50
        , page: true
        , limit: 300
        , limits: [300, 600, 900]
        ,parseData: function(res){
            return {
                "totalRow": {
                    "purchaseNo":"采购单号出现次数："+res.groupCount
                },
                "code": res.status,
                "count": res.total,
                "data": res.data
            };
        }
    });


    form.on('submit(submitform)', function (data) {
        if(isEmpty(operationList.getValue('valueStr')) && isEmpty(salesmanList.getValue('valueStr')) && isEmpty(deptOperationList.getValue('valueStr')) && isEmpty(deptSalesmanList.getValue('valueStr'))){
            data.field.operationCode = user.code;
        }
        table.reload('offertableid', {
            page: {
                curr: 1 //重新从第 1 页开始
            }
            , url: 'carryDetail/statistics/purchaseStatisticsTwoByPage'
            , where: data.field
        }, 'data');
        return false;
    });


    form.on('submit(exportData)', function (queryReq) {
        if(isEmpty(operationList.getValue('valueStr')) && isEmpty(salesmanList.getValue('valueStr')) && isEmpty(deptOperationList.getValue('valueStr')) && isEmpty(deptSalesmanList.getValue('valueStr'))){
            queryReq.field.operationCode = user.code;
        }
        let index = layer.load(2, {
            shade: [0.4, '#000'],
            content: '加载中...',
            success: function (layero) {
                layero.find('.layui-layer-content').css({
                    'padding-top': '40px',
                    'width': '200px'
                });
            }
        });
        $.ajax({
            data: queryReq.field,
            url:"carryDetail/export/purchaseStatisticsTwoExport",
            success: function(res) {
                if(res.status == 200){
                    //配置列宽
                    let colConf = excel.makeColConfig({
                        'A': 80,
                        'X': 80
                    }, 80);
                    excel.exportExcel({
                        sheet1: res.data.data
                    }, '采购排产及计划统计.xlsx', 'xlsx', {
                        extend: {
                            '!cols': colConf
                        }
                    });
                }else {
                    layer.msg(res.msg, {icon: 5});
                }
                layer.close(index);
                return false;
            }
        });
        return false;
    });
    document.getElementById('clear').onclick = function(){
        operationList.setValue([ ]);
        salesmanList.setValue([ ]);
        deliveryDateTypeList.setValue([ ]);
        deptOperationList.setValue([ ]);
        deptSalesmanList.setValue([ ]);
        productDataTypeList.setValue([ ]);
        billNoStatusList.setValue([ ]);
    };
    function isEmpty(obj){
        if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
            return true;
        }else{
            return false;
        }
    }
});